<?php
/*
  Template Name: Visualization Energy
 */

//Logic to save records
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$rubro_id = get_user_meta($user_id, 'rubro_profile', true);

get_template_part('secondary', 'header');
get_template_part('secondary', 'sidebar');

$year = date('Y');
$month = date('m');
$last_year = $year - 1;
$electricity_listings = $wpdb->get_results("SELECT * FROM `bpa_user_info` WHERE (user_id=" . $user_id . " AND kind='electricity' AND rubro_id=" . $rubro_id . ") AND  ((year={$year} AND month<=$month) OR year = '{$last_year}') ORDER BY year DESC ,month LIMIT 12");
$gas_listings = $wpdb->get_results("SELECT * FROM `bpa_user_info` WHERE (user_id=" . $user_id . " AND kind='gas' AND rubro_id=" . $rubro_id . ") AND  ((year={$year} AND month<=$month) OR year = '{$last_year}') ORDER BY year DESC ,month LIMIT 12");
$grouped_electricity_listings = $wpdb->get_results("SELECT rubro_id,month,year ,AVG(price) as price FROM `bpa_user_info`  WHERE kind='electricity' AND rubro_id=" . $rubro_id . "  GROUP BY month,year ORDER BY year,month");
$grouped_gas_listings = $wpdb->get_results("SELECT rubro_id,month,year ,AVG(price) as price FROM `bpa_user_info`  WHERE kind='gas' AND rubro_id=" . $rubro_id . "  GROUP BY month,year ORDER BY year,month");

?>

<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
    <div id="dash-content" class="visualiza-content">
        <?php if (have_posts()) : ?>
            <?php while (have_posts()) : the_post(); ?>
                <header><meta http-equiv="Content-Type" content="text/html; charset=gb18030">
                    <h2><?php the_title(); ?></h2>
                    <h5>&nbsp;</h5>
                </header> 
                <div class="v-canvas">
                    <canvas id="detailed_electricity_chart" width="766" height="500"></canvas>
                    <div id="legend" width="766" height="100"></div>
                </div>
                <div class="visualiza">
                    <div class="v-left">
                        <h3><?php the_title(); ?></h3>
                        <p><?php the_content(); ?></p>
                        <a class="buton agregar" href="<?php echo Helpers::get_user_register_url(); ?>">Agregar nuevo consumo</a>
                    </div>
                    <div class="v-right">
                        <h3>Electricidad</h3>
                        <table>
                            <thead>
                                <tr>
                                    <th>Mes</th>
                                    <th>Consumo Kwh</sup></th>
                                    <th>Monto S/.</th>
                                </tr></thead>
                            <tbody>
                                <?php foreach ($electricity_listings as $field) { ?>
                                    <tr>
                                        <td><?php echo get_year_from_index($field->month) . " " . $field->year; ?></td>
                                        <td class="v-precio"><?php echo $field->consumption; ?></td>
                                        <td class="v-precio">S/.<?php echo sprintf("%.2f", $field->price); ?></td>
                                    </tr> 
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="v-right" style="padding-top:20px;">
                        <h3>Combustible</h3>
                        <table>
                            <thead>
                                <tr>
                                    <th>Mes</th>

                                    <th>Monto S/.</th>
                                </tr></thead>
                            <tbody>
                                <?php foreach ($gas_listings as $field) { ?>
                                    <tr>
                                        <td ><?php echo get_year_from_index($field->month) . " " . $field->year; ?></td>

                                        <td class="v-precio">S/.<?php echo sprintf("%.2f", $field->price); ?></td>
                                    </tr> 
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php endif; ?>
    </div>
</div>

<?php
//TODO: Need to refactor this
$energy = get_metadata('listing_term', $rubro_id, 'base_line_energy', true);
$company_data = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
$grouped_months_data = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
foreach ($electricity_listings as $field) {
    $company_data[$field->month - 1] = $field->price;
}
foreach ($gas_listings as $field) {
    $company_data[$field->month - 1] = sprintf("%.2f", $company_data[$field->month - 1] + $field->price);
}
//Promedio
foreach ($grouped_electricity_listings as $grouped_field) {
    $grouped_months_data[$grouped_field->month - 1] = sprintf("%.2f", $grouped_field->price);
}
foreach ($grouped_gas_listings as $grouped_field) {
    $grouped_months_data[$grouped_field->month - 1] = sprintf("%.2f", $grouped_months_data[$grouped_field->month - 1] + $grouped_field->price);
}
//Now we calculate the remaining ones
?>

<script>
    var electricity_ctx = document.getElementById("detailed_electricity_chart").getContext("2d");
    var electricity_data = {
        labels: ["","Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
        datasets: [
            {
                label: "Consumo mensual de la empresa ",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "#fff",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [0,<?php echo implode($company_data, ","); ?>]
            },
            {

                label: "Consumo promedio del rubro",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "#0f0",
                pointStrokeColor: "#0f0",
                lineColor: "#0f0",
                pointHighlightFill: "#0f0",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [0, <?php echo implode($company_data, ","); ?>]

            },
            {
                label: "Consumo &oacute;ptimo",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "#000",
                pointStrokeColor: "#000",
                lineColor: "#000",
                pointHighlightFill: "#000",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [<?php echo implode(array_fill(0, 13, $energy), ","); ?>]
            },
        
        ]
    };
    var options = {
        scaleShowGridLines : true,
        scaleGridLineColor : "rgba(0,0,0,.05)",
        scaleFontColor: "rgba(255,255,255,1)",
        scaleGridLineWidth : 1,
        bezierCurve : false,
        scaleLabel : "S/. <%= value  %>",
        bezierCurveTension : 0.4,
        pointDot : true,
        pointDotRadius : 5,
        pointDotStrokeWidth : 2,
        pointHitDetectionRadius : 20,
        datasetStroke : true,
        multiTooltipTemplate: "S/. <%= value %>",
        datasetStrokeWidth : 2,
        datasetFill : true,
        responsive: true,
        legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].pointColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
    };
    var myLineChart = new Chart(electricity_ctx).Line(electricity_data, options);
    jQuery("#legend").html(myLineChart.generateLegend());
</script>

<?php get_template_part('secondary', 'footer'); ?>

